import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts/core';
import {
  TooltipComponent,
  TooltipComponentOption,
  LegendComponent,
  LegendComponentOption
} from 'echarts/components';
import { PieChart, PieSeriesOption } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout
]);

type EChartsOption = echarts.ComposeOption<
  TooltipComponentOption | LegendComponentOption | PieSeriesOption
>;

const Chart2: React.FC = () => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chartRef.current) {
      const myChart = echarts.init(chartRef.current);
      const option: EChartsOption = {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          // orient: 'vertical', // 设置图例的布局方式为垂直

          left: 'left',
          // 设置图例的文字颜色
          textStyle: {
            color: '#fff'
          }

        },
        series: [
          {
            name: '种植品种',
            type: 'pie',
            radius: ['45%', '65%'],
            avoidLabelOverlap: false,
            left: 'left',
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold',
                // 颜色设置
                color: '#fff',
              }
            },
            labelLine: {
              show: true,
            },
            data: [
              { value: 100, name: '水稻：100亩' },
              { value: 150, name: '小麦：150亩' },
              { value: 120, name: '玉米：120亩' },
              { value: 50, name: '果蔬：50亩' },
              { value: 192, name: '其它：192亩' }
            ]
          }
        ]
      };
      myChart.setOption(option);

      // 监听窗口大小变化，重新渲染图表
      const handleResize = () => {
        myChart.resize();
      };
      window.addEventListener('resize', handleResize);

      // 清理函数，在组件卸载时销毁 ECharts 实例
      return () => {
        window.removeEventListener('resize', handleResize);
        myChart.dispose();
      };
    }
  }, []);

  return (
    <div className='chart2' style={{ boxSizing: 'border-box' }} >
      {/* 给饼图上面添加一个标头 */}
      <p style={{ textAlign: 'center', fontSize: '20px', fontWeight: 'bold', marginBottom: '10px', color: '#fff' }} >种植面积</p>
      <div ref={chartRef} style={{ width: '100%', height: '300px', color: '#fff', boxSizing: 'border-box', }} ></div>
    </div>

  )
    ;
};

export default Chart2;


